package com.qersoft.controller;

import com.qersoft.entity.QuestionBank;
import com.qersoft.entity.ResponseMessage;
import com.qersoft.service.QuestionBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("question-bank")
public class QuestionBankController {

    @Autowired
    private QuestionBankService questionBankService;

    @PostMapping("/add")
    public boolean addQuestionBank(@RequestBody QuestionBank questionBank) {
        return questionBankService.addQuestionBank(questionBank);
    }

    @PutMapping("/update")
    public boolean updateQuestionBank(@RequestBody QuestionBank questionBank) {
        return questionBankService.updateQuestionBank(questionBank);
    }

    @DeleteMapping("/delete/{id}")
    public boolean deleteQuestionBank(@PathVariable("id") Long id) {
        QuestionBank questionBank = new QuestionBank();
        questionBank.setId(id);
        return questionBankService.deleteQuestionBank(questionBank);
    }

    @GetMapping("/exam/{examId}")
    public List<QuestionBank> getQuestionBankByExamId(@PathVariable("examId") String examId) {
        return questionBankService.getQuestionBankByExamId(examId);
    }

    @GetMapping("/{id}")
    public QuestionBank getQuestionBankById(@PathVariable("id") Long id) {
        return questionBankService.getQuestionBankById(id);
    }
    // 根据条件查询题目列表接口
    @GetMapping("/query/{type}/{subject}")
    public ResponseEntity<List<QuestionBank>> getQuestionsByCondition(QuestionBank condition,
                                                                      @RequestParam(required = false) Integer type,
                                                                      @RequestParam(required = false) String subject) {
        if (type!= null) {
            condition.setType(type);
        }
        if (subject!= null) {
            condition.setSubject(subject);
        }
        List<QuestionBank> questions = questionBankService.getQuestionsByCondition(condition);
        return new ResponseEntity<>(questions, HttpStatus.OK);
    }

    // 批量导入问题
    @PostMapping("/batch-import")
    public ResponseMessage<Boolean> batchImportQuestions(@RequestBody List<QuestionBank> questionBankList) {
        boolean result = true;
        for (QuestionBank questionBank : questionBankList) {
            if (!questionBankService.save(questionBank)) {
                result = false;
                break;
            }
        }
        if(result){
            return ResponseMessage.message(result);
        }else {
            return ResponseMessage.message(result);
        }
    }
}

